package com.hbfec.fileserver.callback;

import org.csource.fastdfs.DownloadCallback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.OutputStream;

/**
 * 自定义的FastDFS回调，用于读取FastDFS文件流，并写入到文件下载输出流
 */
public class CustomDownloadCallback implements DownloadCallback {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomDownloadCallback.class);

    private long currentBytes;
    private OutputStream outputStream;

    public CustomDownloadCallback(OutputStream outputStream) {
        this.currentBytes = 0;
        this.outputStream = outputStream;
    }

    /**
     * 下载回调
     *
     * @param fileSize 文件大小
     * @param data     数据buffer
     * @param bytes    读取的字节大小
     * @return 结果
     */
    public int recv(long fileSize, byte[] data, int bytes) {
        try {
            outputStream.write(data, 0, bytes);
        } catch (Exception ex) {
            LOGGER.error("回调函数中接收从FastDFS获取的文件流时出现异常", ex);
            return -1;
        }
        currentBytes += bytes;
        if (this.currentBytes == fileSize) {
            this.currentBytes = 0;
        }
        return 0;
    }
}
